import { useEffect, useRef, useState } from 'react';
import './App.css';

function BaiduMapNative() {
  const mapRef = useRef(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 动态加载百度地图脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=8fBQZ7F58GMEdK6nwNmpjiM6ov4mTpKq&callback=initBaiduMap`;
    
    // 定义全局初始化函数
    window.initBaiduMap = () => {
      try {
        if (mapRef.current && window.BMap) {
          const map = new window.BMap.Map(mapRef.current);
          const point = new window.BMap.Point(116.404449, 39.914889);
          map.centerAndZoom(point, 12);
          map.enableScrollWheelZoom();
          map.addControl(new window.BMap.NavigationControl());
          map.addControl(new window.BMap.ScaleControl());
          console.log('地图初始化成功');
          setIsLoading(false);
        } else {
          throw new Error('地图容器或BMap对象不存在');
        }
      } catch (err) {
        console.error('地图初始化失败:', err);
        setError('地图初始化失败: ' + err.message);
        setIsLoading(false);
      }
    };
    
    // 处理脚本加载错误
    script.onerror = () => {
      setError('百度地图脚本加载失败');
      setIsLoading(false);
    };
    
    document.head.appendChild(script);
    
    return () => {
      // 清理
      if (document.head.contains(script)) {
        document.head.removeChild(script);
      }
      window.initBaiduMap = null;
    };
  }, []);
  
  return (
    <div className="map-container">
      {isLoading && <div className="loading">地图加载中...</div>}
      {error && <div className="error-message">{error}</div>}
      <div ref={mapRef} className="mapStyle"></div>
    </div>
  );
}

export default BaiduMapNative;